<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

// 审批流程类型
const APPROVAL_TYPE = {
  AND: 'and', // 会签（需要所有审批人同意）
  OR: 'or',   // 或签（一人同意即可）
  SEQUENTIAL: 'sequential' // 顺序审批
};

// 审批人类型
const APPROVER_TYPE = {
  SPECIFIC_USER: 'specific_user',    // 指定成员
  DEPARTMENT_MANAGER: 'department_manager', // 部门主管
  ROLE: 'role',                      // 角色
  SELF_SELECT: 'self_select'         // 发起人自选
};

// 表单字段类型
const FIELD_TYPE = {
  TEXT: 'text',           // 文本框
  TEXTAREA: 'textarea',   // 多行文本
  NUMBER: 'number',       // 数字
  SELECT: 'select',       // 下拉选择
  DATE: 'date',          // 日期
  DATE_RANGE: 'daterange', // 日期范围
  FILE: 'file',          // 附件
  IMAGE: 'image'         // 图片
};

// 添加处理器类型
const HANDLER_TYPE = {
  NOTIFY: 'notify',         // 通知
  UPDATE_STATUS: 'status',  // 更新状态
  TRIGGER_HOOK: 'hook',     // 触发钩子
  RUN_SCRIPT: 'script'      // 执行脚本
};

// 工作流模板列表
const workflowTemplates = ref([
  {
    id: 1,
    name: '请假申请',
    icon: 'vacation',
    description: '员工请假流程',
    enabled: true,
    formFields: [
      {
        id: 1,
        type: FIELD_TYPE.SELECT,
        label: '请假类型',
        required: true,
        options: ['年假', '事假', '病假', '调休', '婚假', '产假'],
        defaultValue: ''
      },
      {
        id: 2,
        type: FIELD_TYPE.DATE_RANGE,
        label: '请假时间',
        required: true,
        defaultValue: []
      },
      {
        id: 3,
        type: FIELD_TYPE.TEXTAREA,
        label: '请假原因',
        required: true,
        defaultValue: ''
      },
      {
        id: 4,
        type: FIELD_TYPE.FILE,
        label: '附件',
        required: false,
        defaultValue: []
      }
    ],
    approvalFlow: [
      {
        id: 1,
        name: '直属主管审批',
        type: APPROVAL_TYPE.SEQUENTIAL,
        approvers: [
          {
            type: APPROVER_TYPE.DEPARTMENT_MANAGER,
            level: 1,
            roles: ['MANAGER'], // 添加角色要求
          }
        ],
        handlers: [ // 添加处理器配置
          {
            type: HANDLER_TYPE.NOTIFY,
            config: {
              template: '您的申请已被{approver}批准',
              channels: ['email', 'im']
            }
          },
          {
            type: HANDLER_TYPE.UPDATE_STATUS,
            config: {
              status: 'approved'
            }
          }
        ]
      },
      {
        id: 2,
        name: '人事审批',
        type: APPROVAL_TYPE.OR,
        approvers: [
          {
            type: APPROVER_TYPE.ROLE,
            roleId: 'HR'
          }
        ]
      }
    ]
  }
]);

// 当前编辑的模板
const currentTemplate = ref(null);
const showTemplateForm = ref(false);

// 创建新模板
function createTemplate() {
  currentTemplate.value = {
    id: workflowTemplates.value.length + 1,
    name: '',
    icon: '',
    description: '',
    enabled: true,
    formFields: [],
    approvalFlow: []
  };
  showTemplateForm.value = true;
}

// 编辑模板
function editTemplate(template) {
  currentTemplate.value = { ...template };
  showTemplateForm.value = true;
}

// 保存模板
function saveTemplate() {
  const index = workflowTemplates.value.findIndex(t => t.id === currentTemplate.value.id);
  if (index > -1) {
    workflowTemplates.value[index] = { ...currentTemplate.value };
  } else {
    workflowTemplates.value.push({ ...currentTemplate.value });
  }
  showTemplateForm.value = false;
}

// 添加表单字段
function addFormField() {
  currentTemplate.value.formFields.push({
    id: Date.now(),
    type: FIELD_TYPE.TEXT,
    label: '',
    required: false,
    defaultValue: ''
  });
}

// 添加审批步骤
function addApprovalStep() {
  currentTemplate.value.approvalFlow.push({
    id: Date.now(),
    name: '',
    type: APPROVAL_TYPE.SEQUENTIAL,
    approvers: []
  });
}

// 删除表单字段
function removeField(fieldId) {
  const index = currentTemplate.value.formFields.findIndex(f => f.id === fieldId);
  if (index > -1) {
    currentTemplate.value.formFields.splice(index, 1);
    ElMessage.success('字段已删除');
  }
}

// 删除审批步骤
function removeStep(stepId) {
  const index = currentTemplate.value.approvalFlow.findIndex(s => s.id === stepId);
  if (index > -1) {
    currentTemplate.value.approvalFlow.splice(index, 1);
    ElMessage.success('步骤已删除');
  }
}

// 添加审批人
function addApprover(step) {
  step.approvers.push({
    type: APPROVER_TYPE.SPECIFIC_USER,
    roles: [],
    userId: null
  });
}

// 添加处理器
function addHandler(step) {
  if (!step.handlers) {
    step.handlers = [];
  }
  step.handlers.push({
    type: HANDLER_TYPE.NOTIFY,
    config: {}
  });
}
</script>

<template>
  <div class="workflow-manager">
    <div class="header">
      <h2>工作流配置</h2>
      <button @click="createTemplate" class="primary-btn">新建模板</button>
    </div>

    <!-- 模板列表 -->
    <div class="template-list">
      <div v-for="template in workflowTemplates" 
           :key="template.id" 
           class="template-card">
        <div class="template-header">
          <div class="template-icon">
            <i :class="template.icon"></i>
          </div>
          <div class="template-info">
            <h3>{{ template.name }}</h3>
            <p>{{ template.description }}</p>
          </div>
          <div class="template-actions">
            <el-switch v-model="template.enabled" />
            <button @click="editTemplate(template)" class="edit-btn">编辑</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 模板编辑表单 -->
    <div v-if="showTemplateForm" class="template-form-modal">
      <div class="template-form">
        <h3>{{ currentTemplate.id ? '编辑模板' : '新建模板' }}</h3>
        
        <!-- 基本信息 -->
        <div class="form-section">
          <h4>基本信息</h4>
          <div class="form-item">
            <label>模板名称</label>
            <input v-model="currentTemplate.name" type="text" />
          </div>
          <div class="form-item">
            <label>描述</label>
            <textarea v-model="currentTemplate.description"></textarea>
          </div>
        </div>

        <!-- 表单字段配置 -->
        <div class="form-section">
          <div class="section-header">
            <h4>表单字段</h4>
            <button @click="addFormField" class="add-btn">添加字段</button>
          </div>
          <div v-for="field in currentTemplate.formFields" 
               :key="field.id" 
               class="field-item">
            <div class="field-header">
              <select v-model="field.type">
                <option v-for="(label, type) in FIELD_TYPE" 
                        :key="type" 
                        :value="type">
                  {{ label }}
                </option>
              </select>
              <input v-model="field.label" placeholder="字段名称" />
              <label>
                <input type="checkbox" v-model="field.required" />
                必填
              </label>
              <button @click="removeField(field.id)" class="remove-btn">删除</button>
            </div>
          </div>
        </div>

        <!-- 审批流程配置 -->
        <div class="form-section">
          <div class="section-header">
            <h4>审批流程</h4>
            <button @click="addApprovalStep" class="add-btn">添加步骤</button>
          </div>
          <div v-for="step in currentTemplate.approvalFlow" 
               :key="step.id" 
               class="step-item">
            <div class="step-header">
              <input v-model="step.name" placeholder="步骤名称" />
              <select v-model="step.type">
                <option v-for="(label, type) in APPROVAL_TYPE" 
                        :key="type" 
                        :value="type">
                  {{ label }}
                </option>
              </select>
              <button @click="removeStep(step.id)" class="remove-btn">删除</button>
            </div>
            <div class="step-content">
              <!-- 审批人配置 -->
              <div class="approvers-section">
                <div class="section-title">
                  <h5>审批人</h5>
                  <button @click="addApprover(step)" class="small-btn">添加审批人</button>
                </div>
                <div v-for="(approver, index) in step.approvers" 
                     :key="index" 
                     class="approver-item">
                  <select v-model="approver.type">
                    <option v-for="(label, type) in APPROVER_TYPE" 
                            :key="type" 
                            :value="type">
                      {{ label }}
                    </option>
                  </select>
                  <!-- 角色选择 -->
                  <div class="role-select">
                    <el-select v-model="approver.roles" 
                              multiple 
                              placeholder="选择角色要求">
                      <el-option label="管理员" value="ADMIN" />
                      <el-option label="主管" value="MANAGER" />
                      <el-option label="人事" value="HR" />
                    </el-select>
                  </div>
                </div>
              </div>

              <!-- 处理器配置 -->
              <div class="handlers-section">
                <div class="section-title">
                  <h5>审批后处理器</h5>
                  <button @click="addHandler(step)" class="small-btn">添加处理器</button>
                </div>
                <div v-for="(handler, index) in step.handlers" 
                     :key="index" 
                     class="handler-item">
                  <select v-model="handler.type">
                    <option v-for="(label, type) in HANDLER_TYPE" 
                            :key="type" 
                            :value="type">
                      {{ label }}
                    </option>
                  </select>
                  <!-- 根据处理器类型显示不同的配置项 -->
                  <div class="handler-config" v-if="handler.type === HANDLER_TYPE.NOTIFY">
                    <input v-model="handler.config.template" 
                           placeholder="通知模板" />
                    <el-select v-model="handler.config.channels" 
                              multiple 
                              placeholder="选择通知渠道">
                      <el-option label="邮件" value="email" />
                      <el-option label="站内信" value="im" />
                      <el-option label="短信" value="sms" />
                    </el-select>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-footer">
          <button @click="saveTemplate" class="save-btn">保存</button>
          <button @click="showTemplateForm = false" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.workflow-manager {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.template-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  background: white;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.template-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.template-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.template-icon {
  width: 48px;
  height: 48px;
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #1890ff;
}

.template-info {
  flex: 1;
}

.template-info h3 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #333;
}

.template-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.template-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.edit-btn {
  padding: 6px 16px;
  border: 1px solid #1890ff;
  border-radius: 4px;
  color: #1890ff;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn:hover {
  background: #e6f7ff;
}

.template-form-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.45);
  backdrop-filter: blur(4px);
  display: flex;
  justify-content: center;
  align-items: center;
}

.template-form {
  background: white;
  border-radius: 8px;
  padding: 24px;
  width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}

.form-section {
  background: white;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.field-item, .step-item {
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 12px;
  transition: all 0.3s;
}

.field-item:hover, .step-item:hover {
  background: #f5f7fa;
}

.field-header, .step-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.field-header select,
.field-header input,
.step-header select,
.step-header input {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.remove-btn {
  padding: 4px 12px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  opacity: 0;
}

.field-item:hover .remove-btn,
.step-item:hover .remove-btn {
  opacity: 1;
}

.remove-btn:hover {
  background: #ff7875;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.primary-btn, .save-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: white;
  border: 1px solid #d9d9d9;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.add-btn {
  background-color: #52c41a;
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.step-content {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #e8e8e8;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title h5 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.approver-item, .handler-item {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  align-items: center;
}

.role-select {
  flex: 1;
}

.handler-config {
  flex: 1;
  display: flex;
  gap: 8px;
}

.small-btn {
  padding: 4px 8px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.small-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}
</style> 